//src/main/java/com/cuit/blog/controller/UserController.java
package com.cuit.blog.controller;
import com.cuit.blog.entity.User;
import com.cuit.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;import org.springframework.ui.Model;
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/findAll")
    public String findAll(Model model) {
        List<User> users = userService.findAll();
        model.addAttribute("users", users);
        return "user/user";
    }
    @GetMapping("/add")
    public String showAddPage(Model model) {

        int nextId = userService.getNextId();
        model.addAttribute("nextId", nextId);
        return "user/add";
    }

    @PostMapping("/save")
    public String saveUser(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/user/findAll";
    }
    @GetMapping("/delete/{id}")
    public String showDeletePage(@PathVariable Integer id, Model model) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "user/delete";
    }

    @PostMapping("/delete/{id}")
    public String deleteUser(@PathVariable Integer id) {
        userService.deleteById( id);
        return "redirect:/user/findAll";
    }
    @GetMapping("/search")
    public String showSearchPage(Model model) {
        return "user/search";
    }

    @PostMapping("/searchResult")
    public String searchResult(@RequestParam Integer userId, Model model) {
        User user = userService.findById(userId);
        model.addAttribute("user", user);
        return "user/result";
    }
    @GetMapping("/edit/{id}")
    public String showEditPage(@PathVariable Integer id, Model model) {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "user/edit";
    }

    @PostMapping("/edit/{id}")
    public String editUser(@PathVariable Integer id, @ModelAttribute User user) {
        userService.save(user);
        return "redirect:/user/findAll";
    }
}
